package com.zy.explore.web.constraints.validator;

import com.zy.explore.web.constraints.InString;
import org.springframework.lang.Nullable;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.List;

/**
 * @author Administrator
 */
public class InStringValidator implements ConstraintValidator<InString, String> {

    private List<String> permits;
    private boolean required;

    @Override
    public void initialize(InString annotation) {
        permits = Arrays.asList(annotation.value());
        required = annotation.required();
    }

    @Override
    public boolean isValid(@Nullable String value, ConstraintValidatorContext context) {
        if (value == null && !required) {
            return true;
        }
        return permits.contains(value);
    }
}
